<?php

// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-03-22
// +—————————————————————————————————————————————————————————————————————


/* 腾讯IM回调 */
namespace app\appapi\controller;

use cmf\controller\HomeBaseController;
use think\Db;

class ImbackController extends HomebaseController{
    
    public function index() {
        
        $rs=[
            'ActionStatus'=>'OK',
            'ErrorCode'=>0,
            'ErrorInfo'=>''
        ];
        

        $data = $this->request->param();
        

        file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 data:'.json_encode($data)."\r\n",FILE_APPEND);
        if(!$data || !$data['SdkAppid']){
            file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 退出1:'."\r\n",FILE_APPEND);
            echo json_encode($rs);
            exit;
        }

        $configpri=getConfigPri();

        if($data['SdkAppid'] != $configpri['im_sdkappid']){
            file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 退出2:'."\r\n",FILE_APPEND);
            echo json_encode($rs);
            exit;
        }
        

        if($data['CallbackCommand']=='State.StateChange'){
            /* 状态变更 */

            $obj=htmlspecialchars_decode($data['Info']);

            $data['Info']=json_decode($obj,true);
            

            file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' data[Info]'.json_encode($data['Info'])."\r\n",FILE_APPEND);

            $uid=$data['Info']['To_Account'];
            $action=$data['Info']['Action'];
            
            if($action=='Login'){
                file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 更新登录:'.$uid."\r\n",FILE_APPEND);
                $info=Db::name('user')
                    ->field('isdisturb')
                    ->where("id='{$uid}'")
                    ->find();
                $online=3;
                file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 用户勿扰开关:'.$info['isdisturb']."\r\n",FILE_APPEND);
                if($info['isdisturb']==1){
                    $online=1;
                }
                
                $result=Db::name('user')
                    ->where("id='{$uid}'")
                    ->update( ['online'=>$online,'last_online_time'=>time()] );

                file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 数据库更新用户信息result:'.json_encode($result)."\r\n",FILE_APPEND);
            }
            if($action=='Logout' || $action=='Disconnect'){
                file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 更新下线:'.$uid."\r\n",FILE_APPEND);
                $result=Db::name('user')
                    ->where("id='{$uid}'")
                    ->update( ['online'=>'0','last_online_time'=>time()] );
                file_put_contents(CMF_ROOT .'log/imback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 数据库更新用户信息result:'.json_encode($result)."\r\n",FILE_APPEND);
                /* 处理关播 */
                $this->stopConversa($uid);
            }
        }
        
        
        echo json_encode($rs);
        exit;

	}
    protected function callbacklog($msg){
		file_put_contents(CMF_ROOT .'log/imback_stop_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 '.$msg."\r\n",FILE_APPEND);
	}
    protected function stopConversa($uid){
        if($uid==''){
            return 4004;
        }

        $this->callbacklog('uid:'.json_encode($uid));

        $info=Db::name('conversa_log')
                ->where("  uid={$uid} or liveuid={$uid} ")
                ->order('id desc')
                ->find();
        $this->callbacklog('info:'.json_encode($info));
		
		
		
        if(!$info){
            return 4006;
        } 
		
        if($info['status'] ==2){
            return 4007;
        }
        
        $nowtime=time();

        $data=[
            'status'=>2,
            'endtime'=>$nowtime,
        ];
        $length=$nowtime - $info['starttime'];
        $sendtype='0'; //用户给主播发
        if($uid==$info['liveuid']){
            $sendtype='1'; //主播给用户发
            if($length < 10){
                $votes=$info['total'];
                reduceVotes($info['liveuid'],$votes,$votes);
                
                Db::name('user_coinrecord')
                    ->where("action in (2,3) and touid = {$info['liveuid']} and showid={$info['showid']}")
                    ->update(['isdeduct'=>1]);

                $data['total']='0';
            }
        }
        
        Db::name('conversa_log')->where("id={$info['id']}")->update($data); 
        
        if($uid==$info['liveuid']){
            Db::name('user')->where("id={$info['uid']}")->update( ['online'=>3] );
        }else{
            Db::name('user')->where("id={$info['liveuid']}")->update( ['online'=>3] );
        }
        
        
		if($info['status']!=0){
			$content='通话时长 '.getLength($length,2);
			/* IM */
			/* 用户给主播发 */
			$ext=[
				'method'=>'call',
				'action'=>'9',
				'type'=>$info['type'],
				'content'=>$content,
			];
			
			#构造高级接口所需参数
			$msg_content = array();
			//创建array 所需元素
			$msg_content_elem = array(
				'MsgType' => 'TIMCustomElem',       //自定义类型
				'MsgContent' => array(
					'Data' => json_encode($ext),
					'Desc' => '',
				)
			);
			//将创建的元素$msg_content_elem, 加入array $msg_content
			array_push($msg_content, $msg_content_elem);
			
			$account_id=(string)$info['uid'];
			$receiver=(string)$info['liveuid'];
			$api=getTxRestApi();
			$type= $sendtype==0 ? 1 : 2;
			$ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
			
			
			
			
			/* 主播给用户发 */
			$ext=[
				'method'=>'call',
				'action'=>'8',
				'type'=>$info['type'],
				'content'=>$content,
			];
			
			#构造高级接口所需参数
			$msg_content = array();
			//创建array 所需元素
			$msg_content_elem = array(
				'MsgType' => 'TIMCustomElem',       //自定义类型
				'MsgContent' => array(
					'Data' => json_encode($ext),
					'Desc' => '',
				)
			);
			//将创建的元素$msg_content_elem, 加入array $msg_content
			array_push($msg_content, $msg_content_elem);
			
			$account_id=(string)$info['liveuid'];
			$receiver=(string)$info['uid'];
			$api=getTxRestApi();
			$type= $sendtype==1 ? 1 : 2;
			$ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
		}
        
        return 0;
    }	
}